package com.example.administrator.ttphonehelper.contact;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.text.TextUtils;

import com.example.administrator.ttphonehelper.bean.ContactBean;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/4/22 0022.
 */
public class ContactManager {
    private Context mContext;
    private List<ContactBean> mList;
    public ContactManager(Context context) {
        mContext = context;
    }
    // 联系人总表
    public final static Uri URI_RAW_CONTACTS = Uri.parse("content://"
            + ContactsContract.AUTHORITY + "/raw_contacts");
    // 数据表data表
    public final static Uri URI_DATA = Uri.parse("content://"
            + ContactsContract.AUTHORITY + "/data");
    // 添加联系人
    public static void addContact(Context context, ContactBean bean)
            throws RemoteException, OperationApplicationException
    {
        // 解析器
        ContentResolver resolver = context.getContentResolver();
        // 增加
        // resolver.insert(URI_RAW_CONTACTS, values)
        // 将所有要操作的动作ContentProviderOperation 将其放入ArrayList集合中，然后再批量处理
        // ，这些操作会放在一个事务中
        ArrayList<ContentProviderOperation> operList = new ArrayList<ContentProviderOperation>();

        // 增加raw_contacts
        ContentProviderOperation op1 = ContentProviderOperation
                .newInsert(URI_RAW_CONTACTS)
                .withValue("display_name", bean.getName()).build();
        operList.add(op1);

        // 增加数据详情data
        // 姓名 假设必填
        ContentProviderOperation op2 = ContentProviderOperation
                .newInsert(URI_DATA).withValue("data1", bean.getName())
                .withValue("mimetype", Constants.MIME_TYPE_NAME)
                .withValueBackReference("raw_contact_id", 0)
                .build();
        operList.add(op2);

        // 手机号码 假设也必须
        ContentProviderOperation op3 = ContentProviderOperation
                .newInsert(URI_DATA).withValue("data1", bean.getMobileTel())
                .withValue("mimetype", Constants.MIME_TYPE_PHONE)
                .withValueBackReference("raw_contact_id", 0)
                .withValue("data2", "2").build();
        operList.add(op3);

        // 家庭电话
        if (!TextUtils.isEmpty(bean.getHomeTel()))
        {
            ContentProviderOperation op = ContentProviderOperation
                    .newInsert(URI_DATA).withValue("data1", bean.getHomeTel())
                    .withValue("mimetype", Constants.MIME_TYPE_PHONE)
                    .withValueBackReference("raw_contact_id", 0)
                    .withValue("data2", "1").build();
            operList.add(op);
        }

        // email
        if (!TextUtils.isEmpty(bean.getEmail()))
        {
            ContentProviderOperation op = ContentProviderOperation
                    .newInsert(URI_DATA).withValue("data1", bean.getEmail())
                    .withValue("mimetype", Constants.MIME_TYPE_EMAIL)
                    .withValueBackReference("raw_contact_id", 0)
                    .build();
            operList.add(op);
        }

        // Photo 将照片的字节数据存储到数据库中
        if (bean.getPhoto() != null)
        {
            ContentProviderOperation op = ContentProviderOperation
                    .newInsert(URI_DATA).withValue("data15", bean.getPhoto())
                    .withValue("mimetype", Constants.MIME_TYPE_PHOTO)
                    .withValueBackReference("raw_contact_id", 0)
                    .build();
            operList.add(op);
        }

        // 将所有的操作执行
        /*
         * 参一：主机 参二：是所有的操作
         */
        try {
            resolver.applyBatch(ContactsContract.AUTHORITY, operList);
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (OperationApplicationException e) {
            e.printStackTrace();
        }

    }
    //查询所有联系人
    public List<ContactBean> queryAll()
    {
        mList = new ArrayList<>();
        //得到解析器
        ContentResolver resolver = mContext.getContentResolver();
        //发出查询命令
        //首先查询所有人员的信息
        Cursor cursor1 = resolver.query(URI_RAW_CONTACTS, null, null, null, null);
        while(cursor1.moveToNext())
        {
            int id = cursor1.getInt(cursor1.getColumnIndex("_id"));
            //根据id去查询用户的详细信息
            Cursor cursor2 = resolver.query(URI_DATA, null,"raw_contact_id=?", new String[]{id+""}, null);

            //初始化联人
            ContactBean bean = new ContactBean();
            bean.set_id(id);
            while(cursor2.moveToNext())
            {
                String mimeType = cursor2.getString(cursor2.getColumnIndex("mimetype"));
                String data1 = cursor2.getString(cursor2.getColumnIndex("data1"));
                String data2 = cursor2.getString(cursor2.getColumnIndex("data2"));
                String data4 = cursor2.getString(cursor2.getColumnIndex("data4"));
                byte[] data15 = cursor2.getBlob(cursor2.getColumnIndex("data15"));

                if(mimeType.equals(Constants.MIME_TYPE_NAME))
                {
                    bean.setName(data1);
                }
                else if(mimeType.equals(Constants.MIME_TYPE_ADDRESS))
                {
                    bean.setAddress(data1);
                }
                else if(mimeType.equals(Constants.MIME_TYPE_COMPANY))
                {
                    bean.setCompany(data1);
                    bean.setPosition(data4);
                }
                else if(mimeType.equals(Constants.MIME_TYPE_PHONE))
                {
                    if("2".equals(data2))
                    {
                        bean.setMobileTel(data1);
                    }
                    else if("1".equals(data2))
                    {
                        bean.setHomeTel(data1);
                    }
                    else if("3".equals(data2))
                    {
                        bean.setWorkTel(data1);
                    }
                }
                else if(mimeType.equals(Constants.MIME_TYPE_PHOTO))
                {
                    bean.setPhoto(data15);
                }
            }
            mList.add(bean);
        }

        return mList;
    }
}
